package com.dwjm.exam.admin;



import utils.ConnectionDatabaseForMySQLUseJdbc1;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AdminDaoImpl implements AdminDao {

    @Override
    public Admin login(String username, String password) {
        String sql = "SELECT * FROM admin WHERE username=? AND password=? AND status=1";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                return extractAdminFromResultSet(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }
        
        return null;
    }

    @Override
    public boolean updateLastLoginTime(int adminId, Date lastLoginTime) {
        String sql = "UPDATE admin SET last_login_time=? WHERE admin_id=?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(1, new Timestamp(lastLoginTime.getTime()));
            pstmt.setInt(2, adminId);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, null);
        }
        
        return false;
    }

    @Override
    public List<Admin> getAllAdmins() {
        String sql = "SELECT * FROM admin";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Admin> adminList = new ArrayList<>();
        
        try {
            conn = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                adminList.add(extractAdminFromResultSet(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }
        
        return adminList;
    }

    @Override
    public Admin getAdminById(int adminId) {
        String sql = "SELECT * FROM admin WHERE admin_id=?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, adminId);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                return extractAdminFromResultSet(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }
        
        return null;
    }

    @Override
    public int addAdmin(Admin admin) {
        // 先检查用户名是否已存在
        if (isUsernameExists(admin.getUsername())) {
            return -1; // 用户名已存在
        }
        
        String sql = "INSERT INTO admin (username, password, real_name, email, phone, role, status) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?)";
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, admin.getUsername());
            pstmt.setString(2, admin.getPassword());
            pstmt.setString(3, admin.getRealName());
            pstmt.setString(4, admin.getEmail());
            pstmt.setString(5, admin.getPhone());
            pstmt.setString(6, admin.getRole());
            pstmt.setInt(7, admin.getStatus());
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                ResultSet generatedKeys = pstmt.getGeneratedKeys();
                if (generatedKeys.next()) {
                    return generatedKeys.getInt(1); // 返回生成的主键
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, null);
        }
        
        return 0;
    }

    @Override
    public boolean updateAdmin(Admin admin) {
        String sql = "UPDATE admin SET password=?, real_name=?, email=?, phone=?, role=?, status=? " +
                    "WHERE admin_id=?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, admin.getPassword());
            pstmt.setString(2, admin.getRealName());
            pstmt.setString(3, admin.getEmail());
            pstmt.setString(4, admin.getPhone());
            pstmt.setString(5, admin.getRole());
            pstmt.setInt(6, admin.getStatus());
            pstmt.setInt(7, admin.getAdminId());
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, null);
        }
        
        return false;
    }

    @Override
    public boolean deleteAdmin(int adminId) {
        String sql = "DELETE FROM admin WHERE admin_id=?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, adminId);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, null);
        }
        
        return false;
    }
    
    // 检查用户名是否已存在
    private boolean isUsernameExists(String username) {
        String sql = "SELECT COUNT(*) FROM admin WHERE username=?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }
        
        return false;
    }
    
    // 从结果集提取管理员信息
    private Admin extractAdminFromResultSet(ResultSet rs) throws SQLException {
        Admin admin = new Admin();
        admin.setAdminId(rs.getInt("admin_id"));
        admin.setUsername(rs.getString("username"));
        admin.setPassword(rs.getString("password"));
        admin.setRealName(rs.getString("real_name"));
        admin.setEmail(rs.getString("email"));
        admin.setPhone(rs.getString("phone"));
        admin.setRole(rs.getString("role"));
        admin.setCreateTime(rs.getTimestamp("create_time"));
        admin.setLastLoginTime(rs.getTimestamp("last_login_time"));
        admin.setStatus(rs.getInt("status"));
        return admin;
    }
    
    // 关闭资源
    private void closeResources(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
} 